package com.youyoulong.framework.util;

import java.util.Locale;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public final class SpringContextUtil implements ApplicationContextAware {

	private SpringContextUtil() {
	}

	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// TODO Auto-generated method stub
		SpringContextUtil.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		// TODO Auto-generated method stub
		return SpringContextUtil.applicationContext;
	}

	public static Object getBean(String beanId) throws BeansException {
		return applicationContext.getBean(beanId);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object getBean(String beanId, Class requiredType) throws BeansException {
		return applicationContext.getBean(beanId, requiredType);
	}

	public static boolean containsBean(String beanId) {
		return applicationContext.containsBean(beanId);
	}

	public static boolean isSingleton(String beanId) throws NoSuchBeanDefinitionException {
		return applicationContext.isSingleton(beanId);
	}

	@SuppressWarnings("rawtypes")
	public static Class getType(String beanId) throws NoSuchBeanDefinitionException {
		return applicationContext.getType(beanId);
	}

	public static String[] getAliases(String beanId) throws NoSuchBeanDefinitionException {
		return applicationContext.getAliases(beanId);
	}

	public static String getCurrentProfile() {
		return applicationContext.getEnvironment().getActiveProfiles()[0];
	}

	public static String getMessage(String key) {
		return getMessage(key, new Object[] {}, ThreadVariableUtil.create().getCurrentLocale());
	}

	public static String getMessage(String key, Locale locale) {
		return getMessage(key, new Object[] {}, locale);
	}

	public static String getMessage(String key, Object[] args) {
		return getMessage(key, args, ThreadVariableUtil.create().getCurrentLocale());
	}
	
	//获取国际化语言参数
	public static String getMessage(String key, Object[] args, Locale locale) {
		return applicationContext.getMessage(key, args, locale);
	}

}
